<template>
  <!--  面包屑导航-->
  <el-breadcrumb separator=">">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!--  卡片区域-->
  <el-card>
    <!--    搜索添加区域-->
    <el-row :gutter="4">
      <el-col :span="8">
        <el-input placeholder="Please input" v-model="userQueryInfo.query" clearable @clear="getUserList">
          <template #append>
            <el-button class="iconfont icon-fenxiang" @click="getUserList"></el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addFormVisible = true">添加用户</el-button>
      </el-col>
    </el-row>
    <!--    用户表格区域-->
    <el-table :data="userList" border stripe>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="手机号"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column prop="mg_state" label="状态">
        <template v-slot="scope">
          <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作"  width="180px">
        <template v-slot="scope">
          <el-tooltip content="修改" placement="top" :enterable="false">
            <el-button v-model="scope.row.Id" @click="showEditDialog(scope.row.id)" type="primary" size="small" class="iconfont icon-edit"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" :enterable="false">
            <el-button type="danger" @click="openMessageBox(scope.row.id)" size="small" class="iconfont icon-delete"></el-button>
          </el-tooltip>
          <el-tooltip content="分配角色" placement="top" :enterable="false">
            <el-button type="warning" @click="showRoleDialog(scope.row)" size="small" class="iconfont icon-star"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
        v-model:currentPage="userQueryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="userQueryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    >
    </el-pagination>

    <!-- 添加用户表单 -->
    <el-dialog v-model="addFormVisible" title="添加用户" @close="closeDialog">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密 码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮 箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">确认</el-button>
      </span>
      </template>
    </el-dialog>

    <!-- 修改用户信息 -->
    <el-dialog v-model="editFormVisible" title="修改用户信息" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮 箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click="editUser">确认</el-button>
      </span>
      </template>
    </el-dialog>
    <!--分配用户角色-->
    <el-dialog v-model="roleVisible" title="分配角色">
      <h4>用户名：{{currentUser.username}}</h4>
      <h4>用户角色：{{currentUser.role_name}}</h4>
      <el-form>
        <el-form-item label="角色选择">
          <el-select v-model="currentSelectedRole" placeholder="请选择你的角色" @change="changeRole">
            <el-option v-for="item in roles"
                       :key="item.id"
                       :label="item.roleName"
                       :value="item.id">

            </el-option>

          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="roleVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {useStore} from "@/store";
import {GetUserList, AddUser, GetUserById, EditUser, DeleteUser, AllRoles, DistributeRole} from "@/api";
import {computed, reactive, ref} from "vue";
import {ElMessage,ElMessageBox} from "element-plus";
import {SaveUserState} from "@/api";
import {IRoles, UserInfo} from "@/util/interface";

const store = useStore()
// 用户列表查询
const userQueryInfo = computed(()=>{
  return store.getters.getUserListInfo
})
const userList = ref([])
const total = computed(()=>{return store.getters.getTotal})
const getUserList = async ()=>{
  const {data: res} = await GetUserList(userQueryInfo.value)
  if (res.meta.status !== 200) { return ElMessage.error('获取用户列表失败') }
  userList.value = res.data.users
  store.commit('setTotal', res.data.total)
}
getUserList()
// 状态更新保存到数据库
const userStateChanged = async (userInfo: UserInfo)=>{
  // console.log(userInfo)
  const {data: res} = await SaveUserState(userInfo)
  if (res.meta.status !== 200) {
    userInfo.mg_state = !userInfo.mg_state
    return ElMessage.error('更新用户状态失败')
  }
  ElMessage.success('更新用户状态成功')
}
// 分页设置
// 监听 page size 改变的事件
const handleSizeChange = ()=>{
  getUserList()
}
// 监听 页码值 改变的事件
const handleCurrentChange = ()=>{
  getUserList()
}
// 添加用户对话框
const addFormVisible = ref(false)
// 添加用户表单绑定的数据对象
const addFormRef: any = ref({})
const addForm: any = reactive({
  username: '',
  password: '',
  email: '',
  mobile: ''
})
// 验证手机号
const checkMobile = (rule: any, value: any, callback: any) => {
  const regMobile = /^(13[0-9]|14[5|7]|15[0-9]|18[0-9])\d{8}$/
  if (regMobile.test(value)){return callback()}
  callback(new Error('请输入正确的手机号'))
}
// 验证邮箱
const checkEmail = (rule: any, value: any, callback: any) => {
  const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
  if (regEmail.test(value)) { return callback()}
  callback(new Error('请输入正确的邮箱'))
}
// 添加用户表单绑定的数据验证规则
const addFormRules = reactive({
  // 验证用户名是否合法
  username: [
    {required: true, message: '请输入登陆用户名', trigger: 'blur'},
    {min: 3, max: 10, message: '长度在3到10个字符', trigger: 'blur'}
  ],
  // 验证密码是否合法
  password: [
    {required: true, message: '请输入登陆密码', trigger: 'blur'},
    {min:6, max: 10, message: '长度在6到15个字符', trigger: 'blur'}
  ],
  // 验证邮箱是否合法
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {validator: checkEmail, trigger: 'blur'}
  ],
  // 验证手机号是否合法
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {min:11, max: 11, message: '手机号长度在11个字符', trigger: 'blur'},
    {validator: checkMobile, trigger: blur}
  ],
})
//关闭对话框的事件
const closeDialog = ()=>{
  addFormRef.value.resetFields()
}
//添加用户
const addUser = ()=>{
  addFormRef.value.validate(async (valid: boolean)=>{
    if(!valid){ return ElMessage.error('用户信息验证不通过') }
    const {data: res} = await AddUser(addForm)
    console.log(res)
    if(res.meta.status !== 201) { return ElMessage.error('添加用户失败')}
    ElMessage.success('添加用户成功')
    getUserList()
    addFormVisible.value = false
  })
}
//修改用户信息
const editForm = ref({
  id: '',
  rid: '',
  username: '',
  mobile: '',
  email: ''
})
const editFormRef: any = ref({})
const editFormVisible = ref(false)
const editFormRules = reactive({
  // 验证邮箱是否合法
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {validator: checkEmail, trigger: 'blur'}
  ],
  // 验证手机号是否合法
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {min:11, max: 11, message: '手机号长度在11个字符', trigger: 'blur'},
    {validator: checkMobile, trigger: blur}
  ],
})
const showEditDialog = async (id: number)=>{
  const {data: res} = await GetUserById(id)
  if(res.meta.status !== 200) {return ElMessage.error('获取用户信息失败')}
  editForm.value = res.data
  editFormVisible.value = true
}
const editDialogClosed = ()=>{
  editFormRef.value.resetFields()
}
const editUser = ()=>{
  editFormRef.value.validate(async (valid: boolean)=>{
    if(!valid) {return ElMessage.error('更新的用户信息不合法')}
    const{data:res} = await EditUser({
      id: editForm.value.id,
      mobile: editForm.value.mobile,
      email: editForm.value.email
    })
    if(res.meta.status !== 200){return ElMessage.error('更新用户信息失败')}
    ElMessage.success('更新用户信息成功')
    editFormVisible.value = false
  })
}
//删除用户信息 消息弹框
const openMessageBox =async (id: number)=>{
  ElMessageBox.confirm(
      '此操作将永久删除用户信息，是否确认删除？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const {data: res} = await DeleteUser(id)
        console.log(res)
        if(res.meta.status !== 200){return ElMessage.error('删除失败')}
        getUserList()
        ElMessage.success('已成功删除用户')
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
}
// 分配角色
const roleVisible = ref(false)
const currentSelectedRole = ref(null)
const currentUser = reactive({
  'id': 0,
  'role_name': '',
  'username': ''
})
//所有的角色信息
const roles = ref<IRoles[]>([])
//打开分配角色对话框
const showRoleDialog = async (role: any)=>{
  //当前用户信息
  console.log(role.id)
  currentUser.id = role.id
  currentUser.role_name = role.role_name
  currentUser.username = role.username
  const {data: res} = await AllRoles()
  console.log(res)
  if(res.meta.status !== 200) {return ElMessage.error('获取所有角色信息失败')}
  roles.value = res.data
  roleVisible.value = true
}
const changeRole = (val: string)=>{
  console.log(val)
}
const confirmRole = async () => {
  console.log(currentSelectedRole.value)
  const {data: res} = await DistributeRole(currentUser.id, currentSelectedRole.value)
  console.log(res)
  if(res.meta.status !== 200) {return ElMessage.error('分配用户角色失败')}
  ElMessage.success('分配用户角色成功')
  getUserList()
  roleVisible.value = false
}

</script>

<style lang="less" scoped>
.el-button{
  //width: 24px;
}
</style>